package servlet;

import dao.DaoFactory;
import entity.Exam;
import entity.Notice;
import utils.DbUtil;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@WebServlet("/StudentNoticeServlet")
public class StudentNoticeServlet extends HttpServlet {

    private static final long serialVersionUID = 7885200761181044427L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/plain; charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        ArrayList<Integer> list = new ArrayList<Integer>();
        Date date = new Date();
        String sdate=(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm")).format(date);

        int m=-1;
        ResultSet rs = DbUtil.executeQuery("select e_id,e_starttime,e_stoptime from exam");
        try{
            while(rs.next())
            {
                if(sdate.compareTo(rs.getString(2))>=0&&sdate.compareTo(rs.getString(3))<=0)
                {
                    if(rs.getInt(1)==m) continue;
                    m = rs.getInt(1);
                    list.add(rs.getInt(1));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        for(int i=0;i<list.size();i++) {
            try {
                List<Notice> notices = DaoFactory.getInstance().getNoticeDao().listNotice(list.get(i));
                //这里需要增加一个根据考试名来进行查找考试的操作，并将新的列表中添加一列或者将第一列改为查找考试姓名的操作
                if (null == notices || notices.size() == 0) break;
                Exam exam = DaoFactory.getInstance().getExamDao().findById(list.get(i));
                Notice temp = new Notice();
                temp.setN_time("");
                temp.setN_text(exam.getE_name());
                notices.add(temp);
                JSONArray jsonArray = JSONArray.fromObject(notices); //List转json
                resp.getWriter().print(jsonArray);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
